package com.leyou.task.job;

import com.leyou.task.lock.ReentrantRedisLock;
import com.leyou.task.lock.SimpleRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
//@Component
public class HelloJob3 {

    @Autowired
    private StringRedisTemplate redisTemplate;



    /**
     * 效果与固定延时执行一致
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void cleanTimeOutOrder() {
        // 实例一把锁
        //SimpleRedisLock lock = new SimpleRedisLock(redisTemplate, "lock");
        // 可重入锁：可以嵌套使用
        ReentrantRedisLock lock = new ReentrantRedisLock(redisTemplate, "rlock");
        // 获取锁
        boolean boo = lock.lock(50);
        // 判断是否获取了锁
        if(!boo){
            // 获取失败
            log.info("获取锁失败，停止定时任务。");
            return ;
        }
        try {
            // 清理订单并加库存回来
            log.info("获取锁成功，执行定时任务 ==> 清理订单并加库存回来============并加库存===>成功添加库");
            Thread.sleep(5000);
        }catch (InterruptedException e) {
            log.error("异常信息："+e.getMessage());
        }finally {
            lock.unlock();
        }
    }
}
